package com.uniledger.exchange.home.scheme.fragment.transfer;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.uniledger.commonlib.easymoney.EasyMoneyEditText;
import com.uniledger.commonlib.easymoney.IconMoneyEditText;
import com.uniledger.commonlib.pinkeyboard.IKeyboardListener;
import com.uniledger.commonlib.pinkeyboard.KeyboardDialog;
import com.uniledger.exchange.R;
import com.uniledger.exchange.contact.UniContact;
import com.uniledger.exchange.glide.GlideApp;
import com.uniledger.exchange.model.OkSingleton;
import com.uniledger.exchange.model.StellarAsset;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.uniledger.commonlib.bigdecimalutils.BigDecimalUtils.is;


/**
 * https://github.com/xyzlf/NumericKeyboard
 * https://github.com/ihgoo/PasswordKeyboard
 */
public class TransferIntoFragment extends TransferFragment implements IKeyboardListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private UniContact contact;
    private StellarAsset stellarAsset;

    BigDecimal totalBalanceBigDecimal;

    @BindView(R.id.img_user_head)
    CircleImageView img_user_head;

    @BindView(R.id.txt_user_name)
    TextView txt_user_name;

    @BindView(R.id.money_transfer_amount)
    IconMoneyEditText iconMoneyEditText;

    @BindView(R.id.label_arrival)
    TextView label_fee;

    @BindView(R.id.label_asset_type)
    TextView label_balance;

    @BindView(R.id.label_reminders)
    TextView label_reminders;

    @BindView(R.id.btn_confirm)
    Button btn_confirm;

    KeyboardDialog pinDialog;

    @BindString(R.string.withdraw_fee)
    String feeStr;

    EasyMoneyEditText edit_transfer_amount;

    public TransferIntoFragment() {
        // Required empty public constructor
    }

    public static TransferIntoFragment newInstance(UniContact contact, StellarAsset stellarAsset) {
        TransferIntoFragment fragment = new TransferIntoFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, contact);
        args.putParcelable(ARG_PARAM2, stellarAsset);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            contact = getArguments().getParcelable(ARG_PARAM1);
            stellarAsset = getArguments().getParcelable(ARG_PARAM2);
        }
    }

    void transferAmount() {
        mListener.getKeyboard().attachTo(edit_transfer_amount);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mListener.getKeyboard().attachTo(edit_transfer_amount);
    }

    @Override
    protected void parseArguments(Bundle bundle) {

    }

    @Override
    protected void initView() {
        edit_transfer_amount = iconMoneyEditText.getMoneyEditText();
        btn_confirm.setOnClickListener(this::onClick);
        edit_transfer_amount.setNumberListener(new EasyMoneyEditText.NumberListener() {
            @Override
            public void exchange(String original, String formatted) {
                //TODO 费率计算
                label_fee.setText(getFees(original));
            }
        });

        edit_transfer_amount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                transferAmount();
            }
        });
    }

    @Override
    protected void initData() {
        GlideApp.with(this)
                .load(contact.getAvatar())
                .placeholder(R.drawable.head)
                .error(R.drawable.head)
                .into(img_user_head);

        totalBalanceBigDecimal = new BigDecimal(OkSingleton.getInstance().getAssetBalance());

        txt_user_name.setText(contact.nick);
        label_fee.setText(getFees("0"));
        label_balance.setText(String.format(getResources().getString(R.string.transfer_label_can),
                OkSingleton.getInstance().getAssetBalance(),
                OkSingleton.getInstance().getCurrencyCode()));
        if (stellarAsset != null) {//扫码
            edit_transfer_amount.setText(stellarAsset.amount);
//            edit_transfer_amount.setCurrencySymbol(stellarAsset.currency);
            iconMoneyEditText.setSymbol(R.drawable.ic_common_aed);
        } else {//联系人之间转账
//            edit_transfer_amount.setCurrencySymbol(OkSingleton.getInstance().getSymbol());
            iconMoneyEditText.setSymbol(R.drawable.ic_common_aed);
        }
    }

    @Override
    public int getViewResourceId() {
        return R.layout.fragment_transfer;
    }


    @Override
    public void onClick(View v) {
        //TODO 判断余额是否充足
        String balance = OkSingleton.getInstance().getAssetBalance();
        String amount = edit_transfer_amount.getValueString();
        if (!is(balance).isNullOrZero() && !is(amount).isNullOrZero() && is(balance).gteq(amount)) {
            showPayKeyBoard();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        mListener.getKeyboard().hideKeyboard();
        if (pinDialog != null) {
            pinDialog.dismiss();
        }
    }

    public void showPayKeyBoard() {
        mListener.getKeyboard().hideKeyboard();
        if (pinDialog == null) {
            pinDialog = new KeyboardDialog(getActivity());
            pinDialog.setKeyboardListener(this);
        }
        pinDialog.show();
    }

    public String getFees(String amount) {
        if (TextUtils.isEmpty(amount)) {
            label_reminders.setVisibility(View.INVISIBLE);
            return String.format(feeStr, 0, "0.5%");
        }

        BigDecimal amountBigDecimal = new BigDecimal(amount);

        if (is(amountBigDecimal).isNullOrZero()) {
            label_reminders.setVisibility(View.INVISIBLE);
            return String.format(feeStr, 0, "0.5%");
        } else if (is(amountBigDecimal).isPositive() && is(amountBigDecimal).lteq(totalBalanceBigDecimal)) {
            BigDecimal feeBigDecimal = new BigDecimal(0.005);
            String string = amountBigDecimal
                    .multiply(feeBigDecimal)
                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toString();
            label_reminders.setVisibility(View.INVISIBLE);
            return String.format(feeStr, string, "0.5%");
        } else {
            label_reminders.setVisibility(View.VISIBLE);
            return String.format(feeStr, 0, "0.5%");
        }

    }

    @Override
    public void onPasswordChange(String pwd) {

    }

    @Override
    public void onPasswordComplete(String pwd) {
        Map<String, String> params = new HashMap<>();
        if (stellarAsset != null) {
            params.put("payee_id", contact.id);
            params.put("currency", stellarAsset.currency);
            params.put("remark", "Pay");
        } else {
            params.put("payee_id", contact.id);
            params.put("currency", OkSingleton.getInstance().getCurrencyCode());
            params.put("remark", "Transfer");
        }
        String amount = edit_transfer_amount.getValueString();
        params.put("amount", amount);
        params.put("AccountId", contact.accountId);
        params.put("name", contact.nick);

        mListener.transfer(params);
    }

    @Override
    public void onForgetPwd() {

    }
}
